<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        canvas{
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <canvas id="canvasWebgl" width="500" height="500"></canvas>

    <!--顶点着色器-->
    <script id="vertex-shader" type="x-shader/x-vertex">
        attribute vec2 aPosition;
        attribute vec4 aColor;
        varying vec4 vColor;
        void main(){
            gl_Position = vec4(aPosition, 0.0, 1.0);
            vColor = aColor;
        }
    </script>
    <!--片元着色器-->
    <script id="fragment-shader" type="x-shader/x-fragment">
        precision highp float;
        varying vec4 vColor;
        void main(){
            gl_FragColor = vColor;
        }
    </script>
    <script>
        const gl = document.getElementById('canvasWebgl').getContext('webgl');
        // 创建顶点着色器和片元着色器
        const vertexShader = gl.createShader(gl.VERTEX_SHADER);
        const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        // 获取着色器源码
        const vertexSource = document.getElementById('vertex-shader').innerText;
        const fragmentSource = document.getElementById("fragment-shader").innerText;
        // 绑定着色器源码
        gl.shaderSource(vertexShader, vertexSource);
        gl.shaderSource(fragmentShader, fragmentSource);
        // 编译着色器源码
        gl.compileShader(vertexShader);
        gl.compileShader(fragmentShader);
        // 创建程序对象
        const program = gl.createProgram();
        gl.attachShader(program, vertexShader);
        gl.attachShader(program, fragmentShader);
        gl.linkProgram(program);
        gl.useProgram(program);

        const vertex = new Float32Array([
          -0.5, -0.5,     1.0, 0.0, 1.0, 1.0,// 第一个点
          0.5, -0.5,      0.8, 0.0, 0.3, 0.3, // 第二个点
          0.0, 0.5,      1.0, 0.4, 0.3, 0.5 // 第三个点
        ])
        // 使用缓冲区绑定顶点数据
        const buffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.bufferData(gl.ARRAY_BUFFER, vertex, gl.STATIC_DRAW);
        const positionLocation = gl.getAttribLocation(program, 'aPosition')
        gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 6*Float32Array.BYTES_PER_ELEMENT, 0);
        gl.enableVertexAttribArray(positionLocation);

        const colorLocation = gl.getAttribLocation(program, 'aColor')
        gl.vertexAttribPointer(colorLocation, 4, gl.FLOAT, false, 6*Float32Array.BYTES_PER_ELEMENT, 2*Float32Array.BYTES_PER_ELEMENT);
        gl.enableVertexAttribArray(colorLocation)

        // 绘制图元
        gl.drawArrays(gl.TRIANGLES, 0, 3)
    </script>
</body>
</html>